﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Reflection;
using System.Linq.Expressions;
using System.Data;

namespace Test
{
	[TestClass]
	public class UnitTestClassBase
	{		
		internal string connectionString;
		protected internal SqlConnection connection;
		

		[TestInitialize]
		public virtual void TestInit() {			
			this.connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
			connection = new SqlConnection(connectionString);
			connection.Open();					
		}
		[TestCleanup]
		public virtual void TestCleanup() {
			connection.Close();
			connection.Dispose();
		}
		public TestContext TestContext { get; set; }

		
		protected long TimedAction(Action timedAction) {
			Stopwatch s = Stopwatch.StartNew();
			timedAction();
			s.Stop();
			return s.ElapsedMilliseconds;
		}

		protected LambdaExpression AsLambda<T>(Expression<Func<IEnumerable<T>>> expression) {
			return expression;
		}

		protected int GetRowCount(string sqlStatement) {
			return GetTable(sqlStatement).Rows.Count;
		}
		object VerifyScalar(string sqlStatement) {
			return GetTable(sqlStatement).Rows[0][0];
		}
		protected	DataTable GetTable(string sqlStatement) {
			SqlCommand selectcmd = new SqlCommand(sqlStatement, this.connection);
			SqlDataAdapter adapter = new SqlDataAdapter(selectcmd);
			DataTable table = new DataTable();
			adapter.Fill(table);
			return table;
		}
		protected void WriteQueryText<T>(IQueryable<T> query) {
			this.WriteQueryText(query.Expression);
		}
		protected void WriteQueryText(Expression expression) {
			DbQueryProvider provider = new DbQueryProvider(this.connection);
			this.TestContext.WriteLine(provider.GetQueryText(expression));
		}
		protected void AreEqual<T>(T expected, T actual, string message = null) {
			TestContext.WriteLine("{0} == {1}", expected, actual);
			Assert.AreEqual(expected, actual, message);
		}

	}
}
